import React from 'react';
import { View, Text, TouchableOpacity, ScrollView,StyleSheet,Image,Keyboard} from 'react-native';
import moment from 'moment'
import navigationhelper from 'src/components/navigationhelper'
import {CalendarList, LocaleConfig} from 'react-native-calendars';
import NavBar from 'src/components/navBar'
import Layer from 'src/components/Layer'
import ScrollableTabView from 'react-native-scrollable-tab-view'
import { deviceWidth,deviceHeight,isIPhoneX} from '../../../util';
import {inject,observer} from "mobx-react/native"
import { List, InputItem, Flex } from '@ant-design/react-native';
import  CardManager from '../../../service/CardManager/index'
import { getBankId, getPovinceAndCityId, transformCardData} from '../../../../src/util'
import Picker from 'react-native-picker'
import NameInput, { InputTypes } from 'src/components/Input/NameInput'
import ActionSheet from "react-native-actionsheet"
import ImagePicker from "react-native-image-crop-picker"
import {uploadCardImage} from "src/service/Auth"


@inject('userAuth','cardManager')

@observer

export default class changeSaveCard extends React.Component {

    constructor(props) {
      super(props);

      this.state = {
        dataArray:[],
        name:'',
        identify:'',
        bankCard:'',
        bankId:'',
        bankPublishCard:'请选择发行卡',
        bankPublishColor:'#BFBFBF',
        phoneNum:'',
        codeNum:'',
        bank:[],

      }
    }
    handleChangeText = (key) => (value) => {
      if (this.state[key] === value) return
      this.setState({ [key]: value })
    }

    componentDidMount=()=>{
      if(this.props.cardManager.banks.length === 0){
        this.props.cardManager.fetchBanks()
      }
      this.mounted = true
    }

    componentWillUnmount () {
      this.mounted = false
    }

    handleShowBankPicker = () => {
      Keyboard.dismiss()
      let payload = {
        pickerConfirmBtnColor: [55, 142, 251, 1],
        pickerCancelBtnColor: [55, 142, 251, 1],
        pickerData: this.props.cardManager.banksPureData,
        selectedValue: this.state.bank,
        pickerBg: [255, 255, 255, 1],
        pickerTitleText: '选择开户行',
        pickerCancelBtnText: '取消',
        pickerConfirmBtnText: '确定',
        onPickerConfirm:data=> {
          let bankid = getBankId(this.props.cardManager.banks,data)
          this.setState({
            bankId:bankid,
            bankPublishCard:data[0],
            bankPublishColor:'#2E2E2E'
          })
        }
      }
      Picker.init(payload)
      Picker.show()
    }
  
    // cellView=(title,content)=>{
    //     return(
    //     <View style={{flexDirection:'row'}}>
    //     <Text style={{color:'#8E8E93',fontSize:14,marginLeft:20}}>{title}
    //     </Text>
    //     <InputItem
    //        style={{marginLeft:20}}
    //         clear
    //         placeholder="标题"
    //         ref={el => this.autoFocusInst = el}
    //       >
    //       </InputItem>
    //       </View>
    //     )
  
    //   }

    // FirstView =(title,content)=>{
    //   return(
    //       <View  style={[styles.viewStyle]}>

    //       </View>
    //   )
    //   }
    handImageUpload = () => {
      this.ActionSheet.show()
    }

    changeSavecashCard=(bank_card,bankId,mobile)=>{
      if(!bank_card){
        return  Layer.showMsg('请输入银行卡号')
      }
      if(this.state.bankPublishCard == '请选择发行卡'){
        return  Layer.showMsg('请选择发行卡')
      }
      if(!mobile){
        return  Layer.showMsg('请输入手机号码')
      }
   
      Layer.showLoading()
      CardManager.refreshCashcard({
        token: this.props.userAuth.token,
        bank_id: bankId,
        bank_card: bank_card,
        mobile: mobile,
      }).then((res)=>{
        Layer.hiddenLoading()
        if(res.status == 'success'){
         Layer.showMsg('提交成功')
         if (this.props.navigation.state.params.callback) {
          this.props.navigation.state.params.callback()
         }
         navigationhelper.goBack() 
        }
        else{
          Layer.showMsg(res.message)
        }
      }).catch((res)=>{
        Layer.hiddenLoading()
        Layer.showMsg(res.message)
      }) 
    }
    render(){
   const {real_name,idcard} =  this.props.userAuth.currentUser
      return(
        <View style={{flex: 1,backgroundColor:'#F5F5F5'}}>
        <NavBar 
          back={()=>{
            navigationhelper.goBack()
                     Picker.hide()
            }} 
          title={'更换储蓄卡'} 
          leftText={'返回'} 
        //   rightButton={<TouchableOpacity
        //     style={{justifyContent:'center', paddingRight: 15, alignItems: 'center', paddingTop: Platform.OS === 'ios' ? (isIPhoneX() ? 30: 10) : 0}}
        //     onPress={this.onConfirmSelectedDay}
        //   >
        //     <Text style={{fontSize: 16, color: '#378EFB', fontFamily: 'PingFang SC'}}>
        //       {'确定'}
        //     </Text>
        //   </TouchableOpacity>}
        />
<ScrollView>
     <List style={{marginTop:20}}>
     <InputItem
           style={styles.inputItem}
           editable={false}
           defaultValue={real_name}
            clear
            // value={this.state.value}
            onChange={value => {
              this.setState({
                name:value
              });
            }}
          >
       <Text style={{fontSize:15}}>真实姓名</Text>
     </InputItem>

     <InputItem
          style={styles.inputItem}
            clear
            onChange={value => {
              this.setState({
                identify:value
              });
            }}
            editable={false}
            defaultValue={idcard}
            // extra={<Text>元</Text>}
          >
          <Text style={{fontSize:15}}>身份证</Text>
      </InputItem>

      <View style={{height:20,backgroundColor:'#F5F5F5'}}/>


      <List style={{flexDirection:'column'}}>
      <InputItem 
         style={styles.inputItem}
       clear  
       onChange={value => { this.setState({
             bankCard:value
       });
         }} 
           defaultValue={this.state.bankCard}
        //  extra={<Text>元</Text>}
            placeholder="请输入储蓄卡号"
            editable={true}
          >
           <Text style={{fontSize:15}}>储蓄卡</Text>
      
          </InputItem>

        <Flex style={{borderRadius:10,position:'absolute',left:deviceWidth-45,width:80,height:36,top:4}}
            onPress={()=>{
              this.handImageUpload()
            }}
            >
            <Image source={require('src/assets/mine/cameraSmall.png')} style={{width:30,height:25}}></Image>
         </Flex> 

          </List>


        <List>
        <InputItem 
         editable={false}
        //  placeholder="请选择发行卡"
         style={styles.inputItem}
         clear  onChange={value => { this.setState({
                bankType:value
         });
         }} 
         extra={
          <Flex onPress={()=>{
            this.handleShowBankPicker()
       }}>
         <Image style={{marginLeft:deviceWidth-140}} source={require('src/assets/icon_arrow_grey.png')}>
         </Image>
         </Flex>
         }
          >
          <View style={{flexDirection:'row'}}>
          <Text style={{fontSize:15,color:'#2E2E2E'}}>发卡行</Text>
            <Text style={{marginLeft:40,fontSize:15,color:this.state.bankPublishColor,width:deviceWidth}}>{this.state.bankPublishCard}</Text>
          </View>
         
          </InputItem>

          </List>
          {/* <View style={{height:20,backgroundColor:'#F5F5F5'}}/> */}
          <InputItem 
           style={styles.inputItem}
          clear  onChange={value => { this.setState({ 
                phoneNum:value
          });
         }} 
        //  extra={<Text>元</Text>}
        
            placeholder={'请输入银行卡预留手机号码'}
            editable={true}
          >
           <Text style={{fontSize:15,color:'#2E2E2E'}}>手机号码</Text>
          </InputItem>

    
        {/* <List style={{flexDirection:'column'}}> */}
{/* 
       <InputItem 
            clear  onChange={value => { this.setState({ });
           }} 
  
          //  extra={<Text>元</Text>}
              placeholder="请输入短信验证码"
              editable={true}
            >
              验证码
  

            </InputItem> */}
  
            {/* <Flex style={{borderRadius:10,position:'absolute',right:20,width:80,height:36,top:4}}
            onPress={()=>{
                console.log('点击了获取验证码')
            }}
            >
            <Text style={{color:'#378EFB',fontSize:15}}>获取验证码</Text>
             </Flex> */}
         {/* </List> */}
    </List>


     <Flex justify='center' style={{borderRadius:10,backgroundColor:'#ff2121',marginLeft:10, marginTop:80,height:50,marginRight:10,alignItems: 'center'}}
      onPress={()=>{
       this.changeSavecashCard(this.state.bankCard,this.state.bankId,this.state.phoneNum)
      }}
     >
     <Text style={{color:'#fff',fontSize:16,fontWeight:'bold',}}>提交</Text>
   
    </Flex>

    <ActionSheet
            ref={o => this.ActionSheet = o}
            options={['拍照', '从手机相册选择', '取消']}
            cancelButtonIndex={2}
            onPress={(index) => {
              var promise = undefined
              if(index === 0) {
                promise = ImagePicker.openCamera({
                  width: 300,
                  height: 400,
                  compressImageQuality: 0.5,
                  cropping: true,
                })
              }else if(index === 1) {
                promise = ImagePicker.openPicker({
                  width: 300,
                  height: 400,
                  compressImageQuality: 0.5,
                  cropping: true
                })
              }
              if(promise) {
                promise.then(image => {
                  Layer.showLoading('开始上传')
                  uploadCardImage({
                    image: image,
                    token: this.props.userAuth.token,
                  }).then((res) => {
                    
                    console.log('结果是:',res)
                    Layer.hiddenLoading()
                    // var bank_id = res.data.bank_id
            
                    // this.props.cardManager.banks.forEach(function (item) {
                    //   if(item.id === bank_id){
                    //     backName = item.name
                    //   }
                    // })
                    this.setState({
                      bankCard:res.data.bank_card_number,
                      bankPublishCard:res.data.bank_name,
                    })

                  })
                })
              }
            }}
        />

    </ScrollView>
     </View>
      ) 
    }

}


const styles = StyleSheet.create({
    viewStyle:{
      height:100,
      backgroundColor:'#fff',
      marginLeft:10,
      marginRight:10,
    },
    inputItem:{
      fontSize:15,
      marginTop:2,
      marginLeft:15
    },
    leftTextStyle: {
      width: 70,
      marginLeft: 16
    },

})